package org.androbuzz;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.SlidingDrawer;
import android.widget.Toast;

public class AndroBuzzOauthClient {
	
	private String TAG = "AndroBuzz.OAuthClient";
	private String consumerKey = "androbuzz.org";
	private String consumerSecret = "************************";
	private String mdisplay_name = "androbuzz";
	private String method = "HMAC-SHA1";
	private String callbackUrl = mdisplay_name + ":///";
	private String mscope = "https://www.googleapis.com/auth/buzz";
	
	private String REQUEST_TOKEN_URL = "https://www.google.com/accounts/OAuthGetRequestToken?scope=";
	private String ACCESS_TOKEN_URL = "https://www.google.com/accounts/OAuthGetAccessToken";
	private String AUTHORIZE_TOKEN_URL = "https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?domain=AndroBuzz&hd=default&xoauth_displayname=AndroBuzz&scope=";
	
	private Context mCtx;
	private String mAuthUrl;
	private AndroBuzzDbAdapter mDb;
	private DefaultOAuthConsumer mConsumer;
	private CommonsHttpOAuthProvider mProvider;
	
	public AndroBuzzOauthClient(Context context) {
		mCtx = context;
		mDb = new AndroBuzzDbAdapter(mCtx);
		mDb.open();
		
		mConsumer = new DefaultOAuthConsumer(consumerKey, consumerSecret);
		try {
			mProvider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL + URLEncoder.encode(mscope, "utf-8"), 
					ACCESS_TOKEN_URL, AUTHORIZE_TOKEN_URL + URLEncoder.encode(mscope, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void requestAuthorization() {
		
		try {
			Log.d(TAG, "Retrieving request token");
			mAuthUrl = mProvider.retrieveRequestToken(mConsumer, callbackUrl);
			
			Log.d(TAG, "Get Provider reponse: " + mProvider.getResponseParameters());
			Log.d(TAG, "Get Authorization URL: " + mProvider.getAuthorizationWebsiteUrl());
		
		} catch (OAuthMessageSignerException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (OAuthNotAuthorizedException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (OAuthExpectationFailedException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (OAuthCommunicationException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		// Redirect user to web browser to grant access
		Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(mAuthUrl));
        mCtx.startActivity(i);
	}
	
	public void retrieveToken() {
		
		Uri uri = ((AndroBuzzActivity) mCtx).getIntent().getData();
		
        if(uri != null) {
        	
          final String access_token = uri.getQueryParameter("oauth_token");
          final String oauth_verifier = uri.getQueryParameter("oauth_verifier");
          
          Log.d(TAG, "Got access token:" + access_token);
          Log.d(TAG, "Got oauth verifier:" + oauth_verifier);
           
          try {
        	  mProvider.retrieveRequestToken(mConsumer, oauth_verifier);
        	  mProvider.retrieveAccessToken(mConsumer, oauth_verifier);
          } catch (OAuthMessageSignerException e) {
        	  // TODO Auto-generated catch block
        	  e.printStackTrace();
			} catch (OAuthNotAuthorizedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (OAuthExpectationFailedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (OAuthCommunicationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
          final String token_secret = mConsumer.getTokenSecret();
          final String token = mConsumer.getToken();
          Toast.makeText(mCtx, "Saving authorization Token" , Toast.LENGTH_SHORT).show();
          mDb.addToken(token, token_secret, oauth_verifier);
          mDb.close();
        }
	}
        
    public void sendRequest(String _url) {
    	
    	URL url = null;
    	try {
			url = new URL(_url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        try {
			HttpURLConnection request = (HttpURLConnection) url.openConnection();
			request.setRequestMethod("GET");
			mConsumer.sign(request);
			request.connect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthMessageSignerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

}
